package com.haitonghop.modules.tamdiem;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.haitonghop.R;
import com.haitonghop.controls.AdsViewControl;
import com.haitonghop.controls.DataCachedControl;
import com.haitonghop.controls.IOnComicChanged;
import com.haitonghop.controls.IOnFinalPage;
import com.haitonghop.controls.ImagePagerAdapter;
import com.haitonghop.controls.OnSaveComic;
import com.haitonghop.data.HaiBLMetalData;
import com.haitonghop.data.TamDiemDetailTopicData;
import com.haitonghop.main.AdsBussiness;
import com.haitonghop.main.ComicBussiness;
import com.haitonghop.network.APIRequestWorker;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;
import com.haitonghop.requester.TamDiemRequester;
import com.haitonghop.utils.AppSettingParams;
import com.haitonghop.utils.FaceBookUtils;
import com.haitonghop.utils.Logger;
import com.haitonghop.utils.Utils;
import com.haitonghop.utils.sqllite.datasource.TopicHaiBlData;

public class TamDiemDetailTopicActivity extends Activity implements IOnFinalPage, IOnComicChanged {

	private ImagePagerAdapter imageTamDiemAdapter;
	private String href = "";
	private String nameTitle = "";
	TamDiemDetailTopicData detailTopicData;
	private int selectedIndex = -0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.tamdiem_detail_activity_layout);
		init();

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			href = extras.getString("href");
			nameTitle = extras.getString("NAME");
			selectedIndex = extras.getInt("index");
		}
		detailTopicData = (TamDiemDetailTopicData) DataCachedControl.getInstance().getCached(DataCachedControl.GIRL_IMAGE_LIST);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		ImageButton moreFunction = (ImageButton) findViewById(R.id.btnMoreFunctions);
		if (moreFunction != null) {
			moreFunction.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					openOptionsMenu();
				}
			});
		}
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					DataCachedControl.getInstance().clearCached(DataCachedControl.GIRL_IMAGE_LIST);
					finish();
				}
			});
		}
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prView);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int itemId = item != null ? item.getItemId() : -1;
		switch (itemId) {
		case 1:
			Logger.logMe("Save default");
			ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).doSaveCommicToDefault(TamDiemDetailTopicActivity.this, imageTamDiemAdapter.getCurrentData(), new OnSaveComic() {

				@Override
				public void onError(int errorCode) {
					processError(errorCode);
				}

				@Override
				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					// TODO Auto-generated
					// method stub

				}

				@Override
				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
				}
			});
			break;
		case 2:
			// Logger.logMe("Save ");
			// ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).doSaveCommic(TamDiemDetailTopicActivity.this,
			// imageTamDiemAdapter.getCurrentData(), new OnSaveComic() {
			//
			// public void onError(int errorCode) {
			// processError(errorCode);
			// }
			//
			// public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData
			// haiBlData) {
			// // TODO Auto-generated
			// // method stub
			//
			// }
			//
			// public void onDoneWithNewTopic(HaiBLMetalData blMetalData,
			// TopicHaiBlData haiBlData) {
			// if (haiBlData != null) {
			// showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() +
			// "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
			// + " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
			// }
			// }
			// });
			// break;
			Utils.downloadPhoto(this, 0, this, imageTamDiemAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		case 3:
			Logger.logMe("facebook");
			FaceBookUtils.doShareFaceBook(imageTamDiemAdapter.getCurrentData(), TamDiemDetailTopicActivity.this);
			break;
		case 4:
			doRefreshPage();
			Logger.logMe("refresh");
			break;
		case 5:
			FaceBookUtils.doShareApplication(this);
			break;
		case 6:
			doComment(imageTamDiemAdapter.getCurrentData());
			break;
		case 7:
			Utils.setWallpaper(this, 0, this, imageTamDiemAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		}
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (ComicBussiness.getInstance(this).getDefaultComicTopic() != null && ComicBussiness.getInstance(this).getDefaultComicTopic().getId() != -1) {
			menu.add(1, 1, 1, "Lưu " + ComicBussiness.getInstance(this).getDefaultComicTopic().getName()).setIcon(R.drawable.ic_save_default);
		}
		menu.add(1, 2, 2, "Lưu").setIcon(R.drawable.ic_saved);
		menu.add(3, 3, 3, "Facebook").setIcon(R.drawable.ic_facebook);
		menu.add(4, 4, 4, "Tải lại").setIcon(R.drawable.ic_refresh);

		menu.add(5, 5, 5, "Chia sẻ App").setIcon(R.drawable.ic_share);
		menu.add(5, 6, 6, "Bình luận").setIcon(R.drawable.ic_comment);
		menu.add(6, 7, 5, "Đặt hình nền").setIcon(R.drawable.ic_wall);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onDestroy() {
		if (imageTamDiemAdapter != null) {
			imageTamDiemAdapter.clearListener();
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			DataCachedControl.getInstance().clearCached(DataCachedControl.GIRL_IMAGE_LIST);
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void processError(int errorCode) {
		String error = "";
		switch (errorCode) {

		case OnSaveComic.CREATE_TOPIC_ERROR:
			error = "Không thể tạo được chủ đ�?.";
			break;
		case OnSaveComic.DB_NOT_FOUND:
			error = "Không tìm thấy tập tin dữ liệu.";
			break;
		case OnSaveComic.DEFAULT_TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�? mặc định.";
			break;
		case OnSaveComic.IMAGE_NOT_FOUND:
			error = "Không có truyện hiển thị.";
			break;
		case OnSaveComic.INSERT_COMIC_ERROR:
			error = "Không thể thêm truyện vào máy.";
			break;
		case OnSaveComic.TOPIC_NAME_INVAILD:
			error = "Tên chủ đ�? không đúng.";
			break;
		case OnSaveComic.TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�?.";
			break;
		}
		if (!error.equals("")) {
			Toast.makeText(TamDiemDetailTopicActivity.this, error, 1000).show();
		}
	}

	void showNotice(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Đóng", null);

		AlertDialog notice = builder.create();
		notice.show();
	}

	void doRefreshPage() {
		onStartUp();
	}

	// private QuickAction mQuickAction;
	// void initActionBar() {
	// mQuickAction =
	// QuickAction.getCommonActionBar(TamDiemDetailTopicActivity.this,
	// ComicBussiness.getInstance(this).getDefaultComicTopic(), new
	// OnActionItemClickListener() {
	//
	// public void onItemClick(int pos) {
	// if(ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).getDefaultComicTopic()
	// == null){
	// if (pos == 0) {
	// ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).doSaveCommic(TamDiemDetailTopicActivity.this,
	// imageTamDiemAdapter.getCurrentData(), new OnSaveComic() {
	//
	// public void onError(int errorCode) {
	// processError(errorCode);
	// }
	//
	// public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData)
	// {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData
	// haiBlData) {
	// if(haiBlData != null){
	// initActionBar();
	// showNotice("Thông báo",
	// "�?ã dùng \""+haiBlData.getName()+"\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
	// +
	// " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
	// }
	// }
	// });
	// } else if (pos == 1) {
	// FaceBookUtils.doShareFaceBook(imageTamDiemAdapter.getCurrentData(),TamDiemDetailTopicActivity.this);
	// } else if (pos == 2) {
	// doRefreshPage();
	// } else if(pos == 3){
	// FaceBookUtils.makeFriend(imageTamDiemAdapter.getCurrentData(),TamDiemDetailTopicActivity.this);
	// }
	// } else {
	// if (pos == 0) {
	// ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).doSaveCommicToDefault(TamDiemDetailTopicActivity.this,
	// imageTamDiemAdapter.getCurrentData(), new OnSaveComic() {
	//
	// public void onError(int errorCode) {
	// processError(errorCode);
	// }
	//
	// public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData)
	// {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData
	// haiBlData) {
	// Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
	// }
	// });
	// } else if (pos == 1) {
	// ComicBussiness.getInstance(TamDiemDetailTopicActivity.this).doSaveCommic(TamDiemDetailTopicActivity.this,
	// imageTamDiemAdapter.getCurrentData(), new OnSaveComic() {
	//
	// public void onError(int errorCode) {
	// processError(errorCode);
	// }
	//
	// public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData)
	// {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData
	// haiBlData) {
	// if(haiBlData != null){
	// initActionBar();
	// showNotice("Thông báo",
	// "�?ã dùng \""+haiBlData.getName()+"\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
	// +
	// " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
	// }
	// }
	// });
	// } else if (pos == 2) {
	// FaceBookUtils.doShareFaceBook(imageTamDiemAdapter.getCurrentData(),TamDiemDetailTopicActivity.this);
	// } else if (pos == 3) {
	// doRefreshPage();
	// } else if(pos == 4){
	// FaceBookUtils.makeFriend(imageTamDiemAdapter.getCurrentData(),TamDiemDetailTopicActivity.this);
	// }
	// }
	//
	// }
	// });
	// }

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	private int lastId = -1;
	long currentRequestId = -1;

	void init() {
	}

	void getDetailTopicFromServer(RequestListener listener) {
		TamDiemRequester tamDiemRequester = TamDiemRequester.getImageList(href, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		tamDiemRequester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(tamDiemRequester);
	}

	private void doComment(final HaiBLMetalData blMetalData) {
		if (blMetalData != null) {
			Intent intent = new Intent(getApplication(), TamDiemCommentActivity.class);
			if (blMetalData != null) {
				intent.putExtra("IMAGE_ID", href);
			}
			startActivity(intent);
		}
		// final Facebook facebook = new Facebook(GlobalData.FACEBOOK_APP_ID) ;
		// boolean isValid = SessionStore.restore(facebook,
		// getApplicationContext());
		// if(isValid){
		// Intent intent = new Intent(getApplication(),
		// TamDiemCommentActivity.class);
		// if(blMetalData != null){
		// intent.putExtra("IMAGE_ID", href);
		// }
		// startActivity(intent);
		// } else {
		// facebook.authorize(this, new DialogListener() {
		//
		// public void onFacebookError(FacebookError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// public void onError(DialogError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// public void onComplete(Bundle values) {
		// if(facebook != null){
		// // TODO Auto-generated method stub
		// SessionStore.save(facebook, getApplicationContext());
		// Intent intent = new Intent(getApplication(),
		// TamDiemCommentActivity.class);
		// if(blMetalData != null){
		// intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
		// }
		// startActivity(intent);
		// }
		// }
		//
		// public void onCancel() {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		// }
	}

	ViewPager viewPager = null;
	AdsViewControl prView = null;
	LinearLayout loading = null;
	LinearLayout loadingError = null;
	TextView imageDescription = null;
	LinearLayout menuBar = null;

	@Override
	public void commicChanged(final HaiBLMetalData blMetalData) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (blMetalData != null) {
					if (blMetalData != null && imageDescription != null) {
						if (blMetalData.getTitleDescription() != null) {
							if(blMetalData.getTitleDescription() != null && blMetalData.getTitleDescription().length() == 0) {
								menuBar.setBackgroundColor(getResources().getColor(android.R.color.transparent));
							} else {
								menuBar.setBackgroundColor(getResources().getColor(R.color.menubar_bg));
							}
							if ("".equals(blMetalData.getTitleDescription())) {
								imageDescription.setVisibility(View.GONE);
							} else {
								if (imageDescription.getVisibility() != View.VISIBLE) {
									imageDescription.setVisibility(View.VISIBLE);
								}
								imageDescription.setText(blMetalData.getTitleDescription());
							}
						}
					}
					// if (commentView != null) {
					// String comment =
					// getResources().getString(R.string.comment_string);
					// if(!blMetalData.getCommentCount().equals(""))
					// comment += "(" + blMetalData.getCommentCount() + ")";
					// commentView.setText(comment);
					// }
				}
			}
		});
	}

	OnClickListener clickListenerComment = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (imageTamDiemAdapter.getCurrentData() != null)
				doComment(imageTamDiemAdapter.getCurrentData());
		}
	};

	TamDiemDetailTopicData tamDiemDetailTopicItem;

	public void onStartUp() {
		viewPager = (ViewPager) findViewById(R.id.view_pager);
		prView = (AdsViewControl) findViewById(R.id.prview);
		loading = (LinearLayout) findViewById(R.id.loadingpage);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		imageDescription = (TextView) findViewById(R.id.imageDescription);
		menuBar = (LinearLayout) findViewById(R.id.menubar);

		loadingError.setVisibility(View.INVISIBLE);
		viewPager.setVisibility(View.INVISIBLE);
		prView.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);

		// menuBar.setVisibility(View.GONE);
		menuBar.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);
		// commentView.setOnClickListener(clickListenerComment);

		if (imageTamDiemAdapter == null) {
			imageTamDiemAdapter = new ImagePagerAdapter(this);
			imageTamDiemAdapter.setComicChanged(this);
		}
		imageTamDiemAdapter.clearData();
		viewPager.setOnPageChangeListener(imageTamDiemAdapter);
		viewPager.setAdapter(imageTamDiemAdapter);

		RequestListener listener = new RequestListener() {

			@Override
			public void onRequestFailed(String errorMsg, Request request) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						imageTamDiemAdapter.clearData();
						loading.setVisibility(View.GONE);
						loadingError.setVisibility(View.VISIBLE);

						doAdsByServer();
					}
				});
			}

			@Override
			public void onRequestComplete(Request request) {
				Logger.logMe(">>>>onRequestComplete");
				// TODO Auto-generated method stub
				if (request instanceof TamDiemRequester && currentRequestId == request.getRequestId()) {
					tamDiemDetailTopicItem = ((TamDiemRequester) request).getImageLists();
					imageTamDiemAdapter.setMetalData(tamDiemDetailTopicItem.getImageList());
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							menuBar.setVisibility(View.VISIBLE);
							loading.setVisibility(View.GONE);
							prView.setVisibility(View.VISIBLE);
							viewPager.setVisibility(View.VISIBLE);
							imageTamDiemAdapter.notifyDataSetChanged();
							imageTamDiemAdapter.onPageSelected(0);
							viewPager.invalidate();

							doAdsByServer();
						}
					});
				}
			}
		};
		if (detailTopicData != null) {
			imageTamDiemAdapter.setMetalData(detailTopicData.getImageList());
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					menuBar.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					prView.setVisibility(View.VISIBLE);
					viewPager.setVisibility(View.VISIBLE);
					imageTamDiemAdapter.notifyDataSetChanged();
					imageTamDiemAdapter.onPageSelected(0);
					viewPager.invalidate();

					if (selectedIndex != -1)
						viewPager.setCurrentItem(selectedIndex, true);
					doAdsByServer();
				}
			});
		} else {
			// khi doi tab can reset lai so page
			// cached lai nhu the nao
			getDetailTopicFromServer(listener);
		}
	}

	public void onRequestComplete(Request request) {

	}

	public void onRequestFailed(String errorMsg, Request request) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFinalPage() {

	}

	public void onComment(HaiBLMetalData data) {
		doComment(data);
	}

	public void onLike(HaiBLMetalData data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFinalItem(HaiBLMetalData data) {

	}
}
